<template>
	<view class="" @click="closepop">
		<scroll-view class="message-list-container" 
		:style="{height: `calc(100vh - ${height+60}px)`}" 
		:scroll-y="true"
			:scroll-top="scrollTop" @scrolltoupper='scrolltoupper' @scrolltolower='scrolltolower'
			:scroll-into-view='viewscroll' @scroll="scroll">
			<!-- <view class="abs" @click="gonewpage">
				<image class="absimg" src="/static/images/js.png" mode=""></image>
			</view> -->
			<view id="message-scroll" style="width:100%" android:focusable="true">
				<view class="no-message" style="margin-top: 20rpx;" v-if="isCompleted">消息已全部加载</view>
				<view v-for="(item,index) in messageList" :key="item.ID" class="t-message" :id="item.ID">
					<view v-if="!item.isRevoked">
						<view class="t-message-item">
							<view class="tim_time" v-show="index == 0">
								{{ item.time | dateFormat }}
							</view>
							<view v-if="index != 0" class="tim_time">
								<span v-if="item.time - messageList[index - 1].time > 5 * 60">
									{{ item.time | dateFormat }}
								</span>
							</view>
							<!-- <TUI-TipMessage v-if="item.type === 'TIMGroupTipElem'" :message="item"></TUI-TipMessage> -->
							<view v-if="item.type !== 'TIMGroupTipElem'"
								:class="item.flow === 'out' ? 't-self-message' : 't-recieve-message'">
								<image class="t-message-avatar" mode="aspectFill" v-if="item.flow === 'in'"
									:src="item.avatar || 'https://sdk-web-1252463788.cos.ap-hongkong.myqcloud.com/component/TUIKit/assets/avatar_21.png'">
								</image>
								<view class="read-receipts" v-if="conversation.type === 'C2C' && item.flow === 'out'">
									<view v-if="item.isPeerRead ">已读</view>
									<view v-else>未读</view>
								</view>
								<view :class="'ites'+index" @longpress="onLongpress(item,index)">
									<!-- <TUI-TextMessage v-if="item.type === 'TIMTextElem'" :message="item"
										:isMine="item.flow === 'out'"></TUI-TextMessage>

									<TUI-ImageMessage v-if="item.type === 'TIMImageElem'" :message="item"
										:isMine="item.flow === 'out'"></TUI-ImageMessage>
									<TUI-VideoMessage v-if="item.type === 'TIMVideoFileElem'" :message="item"
										:isMine="item.flow === 'out'"></TUI-VideoMessage>
									<TUI-AudioMessage v-if="item.type === 'TIMSoundElem'" :message="item"
										:isMine="item.flow === 'out'"></TUI-AudioMessage>
									<TUI-CustomMessage v-if="item.type === 'TIMCustomElem'" :message="item"
										:isMine="item.flow === 'out'"></TUI-CustomMessage> -->
								</view>
								<image class="t-message-avatar" mode="aspectFill" v-if="item.flow === 'out'"
									:src="item.avatar || 'https://sdk-web-1252463788.cos.ap-hongkong.myqcloud.com/component/TUIKit/assets/avatar_21.png'">
								</image>
							</view>
						</view>
					</view>
					<view class="tim_time" style="margin: 40rpx auto;" v-else>
						<span v-if="item.flow === 'out'">你撤回了一条消息</span>
						<span v-else>对方撤回了一条消息</span>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="message-input">
			<!-- <TUI-message-input id="message-input" ref="messageInput" :conversation="conversation"
				@sendMessage="sendMessage" /> -->
		</view>
		<!-- <MessageOperate @deleteMessage='deleteMessage' @quote='quoteMessage' ref="operateRef"></MessageOperate> -->
	</view>
</template>

<script>
	// import TUITextMessage from '../message-elements/text-message/index';
	// import TUIImageMessage from '../message-elements/image-message/index';
	// import TUIVideoMessage from '../message-elements/video-message/index';
	// import TUIAudioMessage from '../message-elements/audio-message/index';
	// // 自定义消息类型 作为引用消息使用
	// import TUICustomMessage from '../message-elements/custom-message/index';
	// import TUIMessageInput from '@/chat/tui-chat/message-input/index';
	// import MessageOperate from '../message-operate/index.vue'
	export default {
		data() {
			return {
				avatar: '',
				userID: '',
				// 当前会话
				messageList: [],
				// 自己的 ID 用于区分历史消息中，哪部分是自己发出的
				nextReqMessageID: '',
				// 下一条消息标志
				isCompleted: false, // 当前会话消息是否已经请求完毕
				scrollTop: 0,
				scrollHeight: 0,
				delmessageList: [],
				isone: true,
				height: uni.getStorageSync('safeAreaInsets').bottom
			};
		},
		components: {
			// TUITextMessage,
			// TUIImageMessage,
			// TUIVideoMessage,
			// TUIAudioMessage,
			// TUICustomMessage,
			// MessageOperate,
			// TUIMessageInput
		},
		// props: {
		// 	conversation: {
		// 		type: Object,
		// 		default: () => {}
		// 	},
		// },
		watch: {
			// conversation: {
			// 	handler: function(newVal) {
			// 		if (!newVal.conversationID) return;
			// 		this.setData({
			// 			conversation: newVal
			// 		}, () => {
			// 			this.getMessageList(newVal);
			// 		});
			// 	},
			// 	immediate: true,
			// 	deep: true
			// }
		},
		onLoad(options){
			console.log(uni.$TUIKit)
			this.getMessageList(options.conversationID)
		},
		mounted() {
			// uni.$TUIKit.getMyProfile().then(res => {
			// 	this.avatar = res.data.avatar;
			// 	this.userID = res.data.userID;
			// });
			// uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived, this);
			// uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_READ_BY_PEER, this.$onMessageReadByPeer, this);
			// uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_REVOKED, this.$onRevokeMessage, this);
		},
		destroyed() {
			// 一定要解除相关的事件绑定
			uni.$TUIKit.off(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived);
		},
		methods: {
			// 自己的消息上屏
			sendMessage(event) {
				// 将自己发送的消息写进消息列表里面
				this.messageList = [event.detail.message, ...this.messageList];
				this.scrollToButtom();
			},
			//消息长按
			onLongpress(item, index) {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select(`.ites${index}`).boundingClientRect((data) => {
							this.$refs.operateRef.open(item, index, data)
						})
						.exec();
				});
			},
			// 引用消息
			quoteMessage(item) {
				this.$refs.messageInput.quote(item)
			},
			// 删除消息
			deleteMessage(obj) {
				let that = this
				that.messageList.splice(obj.index, 1)
				that.delmessageList.push(obj.item)
				let promise = uni.$TUIKit.deleteMessage(that.delmessageList);
				promise.then(function(imResponse) {
					console.log(imResponse);
					// 删除消息成功
				}).catch(function(imError) {
					// 删除消息失败
					console.log('deleteMessage error:', imError);
				});
			},
			gonewpage() {
				console.log('123');
				uni.navigateTo({
					url: `/pages/chat/newKf/bj?admin_id=${this.conversation.userProfile.userID}`
				})
			},
			closepop() {
				this.$refs.operateRef.close();
			},
			// 滚动中
			scroll(e) {
				this.$refs.operateRef.close();
			},
			scrolltolower(e) {
				this.isone = false
				if (this.isCompleted) {
					this.setData({
						isCompleted: true,
					});
					return;
				}
				this.getMessageList(this.conversation);
			},
			//页面到达底部，页面翻转后不用此方法
			scrolltoupper(e) {
				console.log('页面到顶部', e);
			},
			getMessageList(id) {
				
				
				
				let messageList = null;
				chat.getMessageList({conversationID: 'C2Ctest'}).then(function(imResponse) {
				  messageList = imResponse.data.messageList; // 消息列表
				  chat.sendMessageReadReceipt(messageList).then(function() {
				    // 发送C2C消息已读回执成功
				  }).catch(function(imError) {
				    // 发送C2C消息已读回执失败
				  });
				});
				
				
				// 打开某个会话时，第一次拉取消息列表，注意！第一次拉取时不要传入 nextReqMessageID
				let promise = chat.getMessageList({conversationID: 'C2Ctest'});
				promise.then(function(imResponse) {
				  const messageList = imResponse.data.messageList; // 消息列表。
				  const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
				  const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。isCompleted 为 true 时，nextReqMessageID 为 ""。
				});
				
				
				
				if (!this.isCompleted) {
					uni.$TUIKit
						.getMessageList({
							conversationID: id,
							nextReqMessageID: this.nextReqMessageID,
							count: 15
						})
						.then(res => {
							this.nextReqMessageID = res.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
							this.isCompleted = res.data.isCompleted; // 表示是否已经拉完所有消息。
							let messageList = res.data.messageList.filter(item => item.isDeleted == false).reverse()
							this.messageList.push(...messageList)
							console.log(this.messageList);
							this.$nextTick(() => {
								if (this.isone) {
									//进入页面滚动到底部
									this.setData({
										scrollTop: 0
									});
								}
							});
						});
				}
			},
			// 消息已读更新
			$onMessageReadByPeer() {
				this.setData({
					messageList: this.messageList
				});
			},
			//消息撤回
			$onRevokeMessage() {
				//撤回后 isRevoked 属性值为 true
				this.setData({
					messageList: this.messageList
				});
			},
			scrollToButtom() {
				const query = uni.createSelectorQuery().in(this);
				let nodesRef = query.select('#message-scroll');
				nodesRef
					.boundingClientRect(res => {
						this.$nextTick(() => {
							//进入页面滚动到底部
							this.setData({
								scrollTop: res.top
							});
						});
					})
					.exec();
			},
			// 收到的消息
			// $onMessageReceived(value) {
			// 	// 若需修改消息，需将内存的消息复制一份，不能直接更改消息，防止修复内存消息，导致其他消息监听处发生消息错误
			// 	const event = value;
			// 	const list = [];
			// 	event.data.forEach(item => {
			// 		if (item.conversationID === this.conversation.conversationID) {
			// 			list.push(Object.assign(item));
			// 		}
			// 	});
			// 	this.messageList.unshift(...list)
			// 	this.scrollToButtom();
			// },
		}
	};
</script>
<style lang="scss">
	// @import './index.css';
</style>
